﻿using System;
using System.Windows.Forms;
using System.Collections;
using System.Data;

namespace DataUpload
{
    public partial class FrmConnect : Form
    {
        private MainForm _container = null;
        private string[] _config;
        internal DBConnection.DBConnection dbc;
        private bool _configChanged;
        private bool _dbListed;

        public FrmConnect()
        {
            InitializeComponent();
        }

        public FrmConnect(MainForm container)
        {
            InitializeComponent();
            _container = container;
            _configChanged = true;
            _dbListed = false;
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (cboDatabase.Text == "")
            {
                MessageBox.Show("Which database do you want to load to?");
                cboDatabase.Focus();
                return;
            }

            _config[1] = txtHost.Text;
            _config[2] = txtLogin.Text;
            _config[3] = txtPassword.Text;
            _config[4] = cboDatabase.Text;
            _config[6] = dmUpdownConnectionTimeOut.Text;
            _config[7] = dmUpdownCommandTimeOut.Text;
            String connString = "Data Source=" + _config[1] + ";Initial Catalog=" + _config[4] + ";Integrated Security=" + _config[5];
            connString += ";User ID=" + _config[2] + ";Password=" + _config[3];
            connString += ";Connection Timeout = " + _config[6];
            try
            {
                if (dbc != null)
                {
                    dbc.Close();
                    dbc.Dispose();
                }
                dbc = new DBConnection.DBConnection(connString, Int32.Parse(_config[7]));
                dbc.Open();

                DBConnection.FileUtility.UpdateConfig("config.xml", _config[1], _config[2], "", _config[4], _config[5], _config[6], _config[7]);
                _configChanged = false;

                this.Hide();
                if (_container.frmAddFiles == null)
                    _container.frmAddFiles = new FrmAddFiles(_container);
                _container.frmAddFiles.Show();
                _container.frmAddFiles.Focus();
            }
            catch (Exception exc)
            {
                DBConnection.MyDebugClass.LogThis("Try to create a connection with the following connection string\n" + connString, exc);
                MessageBox.Show("Failed to connect to database! Please check your configuration info.");
            }
            finally
            {
                dbc.Close();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            _container.Close();
        }

        private void FrmConnect_Load(object sender, EventArgs e)
        {
            _config = new string[8];
            _config[0] = "."; // local host
            DBConnection.FileUtility.ReadConfig("config.xml", out _config[1], out _config[2], out _config[3], out _config[4], out _config[5], out _config[6], out _config[7]);

            txtLogin.Text = _config[2]; // user
            txtPassword.Text = _config[3]; // pass
            txtHost.Text = _config[1]; // remote server
            cboDatabase.Text = _config[4]; // database
            dmUpdownConnectionTimeOut.Text = _config[6]; // connection timeout
            dmUpdownCommandTimeOut.Text = _config[7]; // command timeout
            if (_config[5].Equals("false", StringComparison.OrdinalIgnoreCase)) // security type
                rdbtnSqlServer.Checked = true;
            else if (_config[5].Equals("true", StringComparison.OrdinalIgnoreCase) || _config[5].Equals("SSPI", StringComparison.OrdinalIgnoreCase))
                rdbtnWindow.Checked = true;
        }

        private void rdbtn_Remote_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbtn_Remote.Checked == true)
                txtHost.Text = _config[1];
            else
                txtHost.Text = _config[0];
            _configChanged = true;
        }

        private void rdbtnSqlServer_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbtnSqlServer.Checked == true)
            {
                txtPassword.Enabled = true;
                txtLogin.Enabled = true;
                _config[5] = "false";
            }
            else
            {
                txtPassword.Enabled = false;
                txtLogin.Enabled = false;
                _config[5] = "true";
            }
            _configChanged = true;
        }

        private void FrmConnect_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible)
                this.Focus();
        }

        private void cboDatabase_Enter(object sender, EventArgs e)
        {
            if (_configChanged || !_dbListed)
            {
                _config[1] = txtHost.Text;
                _config[2] = txtLogin.Text;
                _config[3] = txtPassword.Text;
                _config[4] = cboDatabase.Text;
                _config[6] = dmUpdownConnectionTimeOut.Text;
                _config[7] = dmUpdownCommandTimeOut.Text;
                string connString = "Data Source=" + _config[1] + ";Initial Catalog=;Integrated Security=" + _config[5];
                connString += ";User ID=" + _config[2] + ";Password=" + _config[3];
                connString += ";Connection Timeout = " + _config[6];
                try
                {
                    cboDatabase.Items.Clear();
                    this.Cursor = Cursors.WaitCursor;
                    using (DBConnection.DBConnection temp = new DBConnection.DBConnection(connString, Int32.Parse(_config[7])))
                    {
                        temp.Open();
                        DataTable db = temp.Sp_ExecReader("sp_databases", "databases", null, null);
                        temp.Close();

                        foreach (DataRow row in db.Rows)
                        {
                            string t = row[0].ToString();
                            if (t != "master" && t != "model" && t != "msdb" && t != "tempdb")
                                cboDatabase.Items.Add(t);
                        }
                        temp.Dispose();
                    }
                    _dbListed = true;
                }
                catch (Exception exc)
                {
                    DBConnection.MyDebugClass.LogThis("Attempting get list of databases in " + _config[1], exc);
                    MessageBox.Show("Failed to get list of databases!");
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
        }

        private void controls_TextChanged(object sender, EventArgs e)
        {
            _configChanged = true;
        }
    }
}
